package com.xu.system.service.db.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xu.system.mapper.SysUserRoleMapper;
import com.xu.system.model.entity.SysUserRole;
import com.xu.system.service.db.ISysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户和角色关联表 服务实现类
 * </p>
 *
 * @author 许乾伟
 * @since 2024-12-03 03:53:31
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Override
    public boolean saveUserRole(Long userId, List<Long> roleIds) {
        remove(new QueryWrapper<SysUserRole>().eq(SysUserRole.USER_ID, userId));
        if(CollectionUtils.isEmpty(roleIds)){
            return Boolean.TRUE;
        }
        return saveBatch(roleIds.stream().map(roleId -> new SysUserRole().setUserId(userId).setRoleId(roleId)).collect(Collectors.toList()));
    }

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        return list(new QueryWrapper<SysUserRole>()
                .eq(SysUserRole.USER_ID, userId))
                .stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
    }

    @Override
    public List<Long> getUserIdsByRoleId(Long roleId) {
        return list(new QueryWrapper<SysUserRole>()
                .eq(SysUserRole.ROLE_ID, roleId))
                .stream().map(SysUserRole::getUserId).collect(Collectors.toList());
    }

    @Override
    public Boolean isUse(Long roleId) {
        return count(new QueryWrapper<SysUserRole>().eq(SysUserRole.ROLE_ID, roleId)) > 0;
    }

    @Override
    public Boolean delUserRole(Long userId, Long roleId) {
        return remove(new QueryWrapper<SysUserRole>().eq(SysUserRole.USER_ID, userId).eq(SysUserRole.ROLE_ID, roleId));
    }
}
